package com.lql.core.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lql.common.api.ResultCode;
import com.lql.common.constant.CommonRedisKey;
import com.lql.common.entity.User;
import com.lql.common.util.ObjectUtil;
import com.lql.common.util.ThreadSysUtil;
import com.lql.common.util.ThreadUtil;
import com.lql.integrated.util.JwtUtil;
import com.lql.integrated.util.Redis.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wangjian
 * @date 2019/10/10
 */

@Log4j2
public class JwrInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("auth-token");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        if (ObjectUtil.isEmpty(token)) {
            PrintWriter printWriter = response.getWriter();
            printWriter.write(JSONUtil.toJsonStr(ResultCode.CLIENT_UN_CARRIED_VOUCHER));
            return false;
        }
        String username = null;
        try {
            username = jwtUtil.getUsername(token);
        } catch (Exception e) {
            log.error("JWT解析错误");
        }
        if (StrUtil.isBlank(username)) {
            PrintWriter printWriter = response.getWriter();
            printWriter.write(JSONUtil.toJsonStr(ResultCode.INVALID_CREDENTIAL));
            return false;
        }

        //SysUser sysUser = (SysUser)this.serviceMap.get("sysUserService").getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getAccount, username));
        User sysUser = new User().selectOne(new LambdaQueryWrapper<User>().eq(User::getId, username));
        if (ObjectUtil.isNotEmpty(sysUser)){
            String salt = redisUtil.get(String.format(CommonRedisKey.LOGIN_SALT, username));
            if (ObjectUtil.isEmpty(salt)) {
                PrintWriter printWriter = null;
                try {
                    printWriter = response.getWriter();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                printWriter.write(JSONUtil.toJsonStr(ResultCode.LOGIN_OUT));
                return false;
            }
            ThreadSysUtil.threadLocal.set(sysUser);
            return true;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        ThreadUtil.remove();
    }
}
